# -*- coding: utf-8 -*-
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import db

from emof import core as EMOF
from emof import dumper
from emof import loader

from model import Model

class LoadTagData(webapp.RequestHandler):
    def get(self):
        m_id = self.request.get("m_id")
        c_id = self.request.get("id")
        model = Model.get(m_id)

        rep = loader.Loader().load(model.model_XMI)
        self.response.headers['Content-Type'] = 'application/xml'
        xml = "<r></r>"
        
        tag = rep.findTag(c_id)
        
        template_values = {'id': c_id,
                           'tag': tag}

        path = os.path.join(os.getcwd(), 'xml/Tag.xml')
        xml = template.render(path, template_values)

        self.response.out.write(xml)
                
class SaveTagData(webapp.RequestHandler):
    def post(self):
        m_id = self.request.get("m_id")
        c_id = self.request.get("id")
        name = self.request.get("name")
        value = self.request.get("value")
        elements = self.request.get_all("element")
        
        model = Model.get(m_id)

        rep = loader.Loader().load(model.model_XMI)

        tag = rep.findTag(c_id)
        tag.name = name
        tag.value = value
        
        element = list()
        
        for aex in tag.element:
            aex.tag.remove(tag)
        
        if elements:
            for ae in elements:
                el = rep.findElement(ae)
                if el:
                    element.append(el)
                    el.tag.append(tag)
        
        tag.element = element
        
        model.model_XMI = dumper.Dumper().dump(rep)
        model.put()
                
        self.response.out.write("OK")
        
class CreateTagData(webapp.RequestHandler):
    def get(self):
        m_id = self.request.get("m_id")
        
        if self.request.get("p_id") != "":
            p_id = self.request.get("p_id")
        else:
            p_id = '-1'
            
        model = Model.get(m_id)

        rep = loader.Loader().load(model.model_XMI)
        fact = EMOF.Factory(rep)
        tag = fact.create_Tag()
        tag.name = 'New Tag'
        
        el = rep.findElement(p_id)
        
        if el:
            tag.element.append(el)
            el.tag.append(tag)
        
        model.model_XMI = dumper.Dumper().dump(rep)
        model.put()
                
        self.response.out.write(tag.id + '$$$$' + tag.name)